package com.cloudminds.resttest.api;

import com.cloudminds.resttest.cache.ConfigCache;
import com.cloudminds.resttest.service.AppRTCClient;
import com.cloudminds.resttest.service.NewWebSocketChannelClient;
import com.cloudminds.resttest.utils.SpringContextUtils;
import com.cloudminds.resttest.webrtc.IceCandidate;
import com.cloudminds.resttest.webrtc.SessionDescription;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

@Service
public class NewMessageReceiver implements  NewWebSocketChannelClient.WebSocketChannelEvents
{
	@Override
	public JSONArray onWebSocketMessage(String msg)
	{
		//        if (wsClient.getState() != WebSocketConnectionState.REGISTERED) {
		//            Log.e(TAG, "Got WebSocket message in non registered state.");
		//            return;
		//        }
		JSONArray answer = new JSONArray();
		AppRTCClient.SignalingEvents events = null;
		try
		{
			JSONObject json = new JSONObject(msg);
			String msgId = json.getString("id");
			
			//            if (msgId.equals("registerResponse")) {
			//                String response = json.getString("response");
			//                if (response.equals("rejected")) {
			//                    //this case will be handled in websocketChannelClient
			//                    String detail = json.getString("message");
			//                    reportError("Failed to register: " + detail);
			//                } else {
			//                    Log.d(TAG, "Register to hari server completed.");
			//                    wsState = ConnectionState.CONNECTED;
			//                    events.onSignalServerConnected();
			//                }
			//            }
			//            else
			
			//events.onChannelSignalError("WebSocket message JSON parsing error: " + e.toString());
			
			
			if (msgId.equals("callResponse"))
			{
				
				if (json.has("response"))
				{
					String response = json.getString("response");
					if (response.equalsIgnoreCase("ongoing"))
					{
						//indicates the call session is created in server side but not accepted by HI
						String sid = json.getString("sid");
						if (!sid.isEmpty()) { events.onCallSessionCreated(sid); }
						else { events.onChannelSignalError("Invalid sessionId within callStartResponse"); }
					}
					else if (response.equals("rejected"))
					{
						String detail = json.getString("message");
						if (detail.equals("Busy, no free helper"))
						{
							events.onChannelCallRejected(detail);
						}
						else if (detail.equals("Invalid session id"))
						{
							events.onChannelCallRejected("服务已结束");
						}
						else
						{
							events.onChannelCallRejected("Failed to call for assistance: " + detail);
						}
					}
					else
					{ //accepted
						
						String sid = json.getString("sid");
						events.onCallSessionCreated(sid);
						
						if (json.has("sdpAnswer"))
						{
							String answer1 = json.getString("sdpAnswer");
							System.out.println("Received Sdp Answer: " + answer1);
							SessionDescription sdpAnswer = new SessionDescription(SessionDescription.Type.fromCanonicalForm("answer"), answer1);
							events.onCallAccepted(sdpAnswer);
						}
					}
				}
				else
				{
					String reason = json.getString("reason");
					//                    if(reason.equals("reject")){
					if (reason.equals("reject") && json.getString("message").equals("User declined")) { events.onChannelSignalError(reason); }
					else if (reason.equals("reject") && json.getString("message").equals("User busy"))
					{
						events.onChannelSignalError(reason);
					}
					else
					{
						events.onChannelSignalError(json.getString("message"));
					}
				}
			}
			else if (msgId.equals("callUpdate"))
			{
				//String peerName = json.getString("peer");
				IceCandidate candidate = null;
				if (json.has("candidate"))
				{
					JSONObject serverCandidate = json.getJSONObject("candidate");
					System.out.println("IceCandidate Message Received: " + serverCandidate.getString("candidate") + ", " + serverCandidate.getString("sdpMid") + ", " + serverCandidate.getString("sdpMLineIndex"));
					candidate = new IceCandidate(serverCandidate.getString("sdpMid"), serverCandidate.getInt("sdpMLineIndex"), serverCandidate.getString("candidate"));
				}
				String sid = json.getString("sid");
				events.onCallUpdate(sid, candidate);
			}
			else if (msgId.equals("callUpdateResponse"))
			{
				//String peerName = json.getString("peer");
				IceCandidate candidate = null;
				String sid = json.getString("sid");
				events.onCallUpdate(sid, candidate);
			}
			else if (msgId.equals("heartbeatResponse"))
			{
				String sid = json.getString("sid");
				events.onHeartbeatResponse(sid);
			}
			else if (msgId.equals("callStop"))
			{
				String detail = "";
				if (json.has("message")) { detail = json.getString("message"); }
				String sid = json.getString("sid");
				events.onCallStop(sid, detail);
			}
			else if (msgId.equals("objectIdentified"))
			{
				String objectName = json.getString("name");
				if (objectName != null && objectName.length() > 0)
				{
					events.onObjectIdentified(objectName);
				}
			}
			else if (msgId.equals("faceIdentified"))
			{
				System.out.println("ws: faceIdentified" + json);

				/*String faceName = json.getString("name");
				if (faceName != null && faceName.length() > 0)
				{
					events.onFaceIdentified(faceName);
				}

				System.out.println("ws: faceIdentified" + json);
				String questin = json.getJSONObject("data").getJSONObject("question").getString("text");

				ConfigCache.instance().setAyncMessage(json.getString("sid") + "_" + questin, json);*/
			}
			else if (msgId.equals("navigationCommand"))
			{
                /*TODO
                type：0 代表模式切换
                command：1.人工模式；0.ai模式 （int）

                type：1 代表平移
                command：L 左 R 右 F 前进... （String）
                value：代表具体的数值。

                type：2 代表旋转
                command：代表旋转的角度 （double）
                 */
				String command = json.getString("command");
				if (command != null && command.length() > 0)
				{
					events.onCommandReceived(json.toString());
					//                    events.onCommandReceived(command);
				}
				System.out.println("naviCommand:" + json.toString());
			}
			else if (msgId.equals("slamNavigationStart"))
			{
				String startPoint = json.getString("startingPoint");
				String finishingPoint = json.getString("finishingPoint");
				if (startPoint != null && startPoint.length() > 0 && finishingPoint != null && finishingPoint.length() > 0)
				{
					events.onSlamNavigationStart(startPoint, finishingPoint);
				}
			}
			else if (msgId.equals("info"))
			{
				
				System.out.println("ws: onInfo" + json);
				String questin = json.getJSONObject("data").getJSONObject("question").getString("text");
				//testText返回
				ConfigCache.instance().setAyncMessage(json.getString("sid") + "_" + questin, json);
				//String seq = json.getString("seq");
				//音频文件返回
				ConfigCache.instance().setAyncMessage(json.getString("sid")+"_",json);
				//人脸
				ConfigCache.instance().setAyncMessage(json.getString("sid")+"_fr",json);

				//30秒
				ConfigCache.instance().setAyncMessage(json.getString("sid")+"_CheckAction",json);

				try {
					RestApi restApi = (RestApi) SpringContextUtils.getApplicationContext().getBean("restApi");
					System.out.print("=======notifyAll");
					synchronized (restApi.getApiWaiter()){
						restApi.getApiWaiter().notifyAll();
					}

				} catch (Exception e) {
					e.printStackTrace();
				}
			}



		}
		catch (JSONException e)
		{
			events.onChannelSignalError("WebSocket message JSON parsing error: " + e.toString());
		}
		return answer;
	}



	@Override
	public void onWebSocketClose() {

	}

	@Override
	public void onWebSocketConnectError(String description) {

	}

	@Override
	public void onWebSocketRegisterError(String description) {

	}

	@Override
	public void onWebSocketRegisterred(JSONObject data) {

	}


}
